package com.logic.saas.util;

import java.io.IOException;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;

public class JsonResult implements Result {

	private static final long serialVersionUID = 8072145624362435874L;

	private static final Logger log = Logger.getLogger(JsonResult.class);

	private String target = "result";

	private String datePattern = "yyyy-MM-dd";

	private String excludes;
	
	private String contentType;

	public JsonResult() {
		super();
	}

	public String getExcludes() {
		return excludes;
	}

	public void setExcludes(String excludes) {
		this.excludes = excludes;
	}

	public String getDatePattern() {
		return datePattern;
	}

	public void setDatePattern(String datePattern) {
		this.datePattern = datePattern;
	}

	public String getTarget() {
		return target;
	}

	public void setTarget(String target) {
		this.target = target;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public void execute(ActionInvocation actioninvocation){
		try {
			ActionContext actionContext = actioninvocation.getInvocationContext();
			Object obj = actionContext.get(this.target);
			if (null == obj) {
				obj = actionContext.getValueStack().findValue(this.target);
			}
			String json = JsonUtils.toJSON(obj, this.parseExcludes(this.excludes),this.datePattern);
			log.debug(json);
			HttpServletResponse response = ServletActionContext.getResponse();
			String contantType = this.getContentType();
			if(StringUtils.isBlank(contantType)){
				contantType = "text/json; charset=UTF-8";
			}
			response.setContentType(contantType);
			response.getWriter().write(json);
		} catch (IOException e) {
			e.printStackTrace();
			log.error(e);
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e);
		}
	}

	private String[] parseExcludes(String s) {
		if (null == s || s.trim().equals("")) {
			return null;
		}
		StringTokenizer tokenizer = new StringTokenizer(s.trim(), ",");
		String[] attrs = new String[tokenizer.countTokens()];
		int i = 0;
		while (tokenizer.hasMoreTokens()) {
			attrs[i++] = tokenizer.nextToken();
		}
		return attrs;
	}
}
